<template>
    <div id="notice-detail">
        <el-row class="card-box">
            <el-card class="form-box">
                <el-form :label-position="labePosition" label-width="130px" size="mini">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="规则名称:">
                                <el-input v-model="ruleForm.ruleName" clearable style="width: 70%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="启用状态:">
                                <el-select
                                    size="mini"
                                    v-model="ruleForm.status"
                                    style="width: 70%"
                                    :class="ruleForm.status === '1' ? 'red-color' : ruleForm.status === '0' ? 'green-color' : ''"
                                >
                                    <el-option v-for="(value, key) in Dict.statusPojo" :key="key" :label="value" :value="key" :style="getStyle(key)">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="规则生效日期:">
                                <el-date-picker
                                    v-model="ruleForm.dates"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    style="width: 67%"
                                    @change="handleDate"
                                    value-format="yyyyMMdd"
                                    format="yyyy-MM-dd"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="模板类型:">
                                <el-select
                                    v-model="ruleForm.noticeType"
                                    placeholder="请选择"
                                    filterable
                                    style="width: 70%"
                                    @change="handleParams('noticeType')"
                                >
                                    <el-option v-for="(value, key) in Dict.noticeTypePojo" :key="key" :label="value" :value="key"> </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知日历类型:">
                                <el-select
                                    v-model="ruleForm.dateType"
                                    placeholder="请选择"
                                    filterable
                                    style="width: 70%"
                                    @change="() => (ruleForm.specifyPeriod = '')"
                                >
                                    <el-option v-for="(value, key) in Dict.dateTypePojo" :key="key" :label="value" :value="key"> </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="指定周期/日期:">
                                <el-select
                                    v-model="ruleForm.specifyPeriod"
                                    placeholder="请选择"
                                    filterable
                                    clearable
                                    style="width: 70%"
                                    v-if="ruleForm.dateType == '2'"
                                >
                                    <el-option v-for="(value, key) in Dict.specifyPeriodPojo" :key="key" :label="value" :value="key"> </el-option>
                                </el-select>
                                <el-date-picker
                                    v-model="ruleForm.specifyPeriod"
                                    type="date"
                                    style="width: 67%"
                                    value-format="yyyyMMdd"
                                    format="yyyy-MM-dd"
                                    v-else-if="ruleForm.dateType == '3'"
                                >
                                </el-date-picker>
                                <el-input
                                    v-model="ruleForm.specifyPeriod"
                                    style="width: 70%"
                                    :disabled="!['2', '3'].includes(ruleForm.dateType)"
                                    v-else
                                    placeholder="仅当选择按周、按月,联动选择"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="发送时间点:">
                                <el-time-picker
                                    v-model="ruleForm.startTime"
                                    :disabled="ruleForm.executionMethod == '1'"
                                    value-format="HHmm"
                                    format="HH:mm"
                                    style="width: 70%"
                                >
                                </el-time-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="执行方式:">
                                <el-select
                                    placeholder="请选择"
                                    filterable
                                    v-model="ruleForm.executionMethod"
                                    style="width: 70%"
                                    @change="handleParams('executionMethod')"
                                >
                                    <el-option v-for="(value, key) in Dict.executionMethodPojo" :key="key" :label="value" :value="key"> </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="自动通知次数上限:">
                                <el-input v-model="ruleForm.limitTimes" @input.native="onInput" style="width: 70%" clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="数据生成类型:">
                                <template slot="label">
                                    <span>
                                        <el-tooltip>
                                            <div slot="content">自动计算：每天系统自动风控计算；手工计算：由人为触发，在功能页面点击计算。</div>
                                            <i class="el-icon-question"></i>
                                        </el-tooltip>
                                        数据生成类型:
                                    </span>
                                </template>
                                <el-select v-model="ruleForm.calcType" placeholder="请选择" filterable style="width: 70%">
                                    <el-option v-for="(value, key) in Dict.calcTypePojo" :key="key" :label="value" :value="key"> </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" v-if="ruleForm.noticeType != '15'">
                            <el-form-item label="接收角色:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    clearable
                                    filterable
                                    collapse-tags
                                    v-model="ruleForm.notifier"
                                    style="width: 70%"
                                    @change="changeAccountControlValue(ruleForm.notifier, 'notifier')"
                                >
                                    <el-option
                                        v-for="item in roleInfo"
                                        :key="item.roleCode"
                                        :label="item.roleCode + ' ' + item.roleName"
                                        :value="item.roleCode"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" v-if="ruleForm.noticeType != '15'">
                            <el-form-item label="主送用户:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    clearable
                                    filterable
                                    collapse-tags
                                    v-model="ruleForm.noticeUser"
                                    style="width:70%"
                                    @change="changeAccountControlValue(ruleForm.noticeUser, 'noticeUser')"
                                >
                                    <el-option
                                        v-for="item in userStorage"
                                        :key="item.userCode"
                                        :label="item.userName + ' ' + item.userNickName"
                                        :value="item.userCode"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8" v-if="ruleForm.noticeType != '15'">
                            <el-form-item label="抄送用户:">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    clearable
                                    filterable
                                    collapse-tags
                                    v-model="ruleForm.noticeCCuser"
                                    style="width:70%"
                                    @change="changeAccountControlValue(ruleForm.noticeCCuser, 'noticeCCuser')"
                                >
                                    <el-option
                                        v-for="item in userStorageTemp"
                                        :key="item.userCode"
                                        :label="item.userName + ' ' + item.userNickName"
                                        :value="item.userCode"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </el-row>
        <el-row class="card-box" v-if="!$attrs.ShowOperation">
            <el-card>
                <div class="btns">
                    <el-button @click="$emit('close-tab', data.name)">取消</el-button>
                    <el-button v-if="isShowSubmit" type="primary" @click="submit" :loading="btnLoading">确认</el-button>
                </div>
            </el-card>
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import RiskEntryInputs from '@/common/components/risk-entry-inputs.vue';
import WarningNotice from '../dict/warning-notice';
import { changeOptions } from '@/utils/tools';
import XEUtils from 'xe-utils';

@Component({
    name: 'WarningNoticeDetailStaticRiskDisposal',
    components: {
        RiskEntryInputs,
    },
})
export default class WarningNoticeDetailStaticRiskDisposal extends Vue {
    @Prop() data: any;

    Dict = new WarningNotice();

    private labePosition: string = 'right';

    private ruleForm = {
        ruleName: '',
        noticeType: '14',
        dateType: '0',
        dates: [XEUtils.toDateString(new Date(), 'yyyyMMdd'), '20990101'],
        startDate: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        endDate: '20990101',
        status: '0',
        specifyPeriod: '',
        startTime: '',
        executionMethod: '0',
        limitTimes: null,
        calcType: '0',
        notifier: [], // 通知角色
        noticeUser: [],
        noticeCCuser: [],
    };

    private noticeTypeStorage: any[] = [
        { dictKey: '1', dictKeyName: '日终指标报告' },
        { dictKey: '1', dictKeyName: '连续超限处置' },
        { dictKey: '1', dictKeyName: 'OA待办提醒' },
    ];

    private fundGroup: any[] = [];

    private userStorage: any[] = [];

    private userStorageTemp: any[] = [];

    private showType: string = 'addStaticRiskDisposal';

    private btnLoading: boolean = false;

    private userList = []; // 用户列表

    private roleInfo = []; // 剔除角色

    get isShowSubmit() {
        return ['addStaticRiskDisposal', 'editStaticRiskDisposal'].includes(this.showType);
    }

    // 监听父组件带进来的基础数据
    @Watch('data', { immediate: true, deep: true })
    watchData(newData) {
        if (newData) {
            console.log('newData', newData);
            if (newData.content) {
                let data = JSON.parse(JSON.stringify(newData.content));
                data.dates = [String(...(data.startDate || '')), String(...(data.endDate || ''))];
                let timefor = '';
                if (data.startTime != undefined && data.startTime !== '') {
                    timefor = String(data.startTime);
                    // 补全时间格式
                    if (String(data.startTime).length < 4) {
                        for (let i = 0; i < 4 - String(data.startTime).length; i++) {
                            timefor = '0' + timefor;
                        }
                    }
                }
                data.startTime = timefor;
                console.log(timefor, 'timefor----');
                this.ruleForm = { ...this.ruleForm, ...data };
            }
            this.showType = newData.type;
        }
    }

    mounted() {
        console.log(this.Dict.statusPojo);
        this.getRoleInfo();
        this.getUserList();
    }

    // 处理日期
    private handleDate(val: any) {
        if (val && val.length) {
            this.ruleForm.startDate = val[0];
            this.ruleForm.endDate = val[1];
            return;
        }
        this.ruleForm.startDate = '';
        this.ruleForm.endDate = '';
    }

    // 获取通知角色数据
    private getRoleInfo(): void {
        this.$axios.get('/role/query/all').then((res: any) => {
            this.roleInfo = [];
            for (let item of res) {
                if (item.sourceType === '1') {
                    this.roleInfo.push(item);
                }
            }
            if (this.showType != 'addStaticRiskDisposal') {
                // 非新增状态时数据回显
                this.changeAccountControlValue(this.ruleForm.notifier, 'notifier');
            }
        });
    }

    private getUserList(): void {
        this.$axios.get('/userManage/user/list').then((res: any) => {
            if (res) {
                this.userStorage = res;
                this.userStorageTemp = JSON.parse(JSON.stringify(res));
            }
            if (this.showType != 'addStaticRiskDisposal') {
                // 非新增状态时数据回显
                this.changeAccountControlValue(this.ruleForm.noticeUser, 'noticeUser');
                this.changeAccountControlValue(this.ruleForm.noticeCCuser, 'noticeCCuser');
            }
        });
    }

    // 下拉框数据置顶
    private changeAccountControlValue(val: any = [], field): void {
        // 下拉框选中数据置顶
        if (field == 'noticeUser') {
            this.userStorage = changeOptions(val, this.userStorage, 'userCode');
        } else if (field == 'noticeCCuser') {
            this.userStorageTemp = changeOptions(val, this.userStorageTemp, 'userCode');
        } else if (field == 'notifier') {
            this.roleInfo = changeOptions(val, this.roleInfo, 'roleCode');
        }
    }

    private handleParams(param: string) {
        if (param == 'noticeType' && this.ruleForm[param] == '15') {
            this.ruleForm.noticeUser = [];
            this.ruleForm.noticeCCuser = [];
            this.ruleForm.notifier = [];
        } else if (param == 'executionMethod') {
            if (this.ruleForm.executionMethod == '1') {
                this.ruleForm.startTime = '';
            }
        }
    }

    // 通知次数上限(整数)
    private onInput(e) {
        e.target.value = e.target.value.replace(/[^0-9]/g, '');
    }

    // 确认
    private submit() {
        if (!this.verify()) {
            return;
        }
        this.btnLoading = true;
        if (!this.ruleForm.startTime) {
            this.ruleForm.startTime = null;
        }
        if (this.showType == 'editStaticRiskDisposal') {
            this.realSubmit();
            return;
        }
        this.$axios({ url: '/notice/monitor/rule/check', method: 'post', data: this.ruleForm })
            .then((res: any) => {
                if (res) {
                    this.$confirm('已有相同规则，是否继续新增', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                    })
                        .then(() => {
                            this.realSubmit();
                        })
                        .catch(() => {});
                } else {
                    this.realSubmit();
                }
            })
            .catch(() => {})
            .finally(() => {
                this.btnLoading = false;
            });
    }

    // 校验后的提交
    private realSubmit() {
        let urlType = {
            addStaticRiskDisposal: '/notice/monitor/rule/add',
            editStaticRiskDisposal: '/notice/monitor/rule/update',
        };
        let url = urlType[this.showType];
        this.$axios({ url, method: 'post', data: this.ruleForm })
            .then((res: any) => {
                this.yh_message_success('操作成功！');
                this.$emit('close-tab', this.data.name);
            })
            .catch(() => {})
            .finally(() => {
                this.btnLoading = false;
            });
    }

    // 校验字段
    private verify() {
        if (!this.ruleForm.ruleName) {
            this.yh_message_warn('规则名称不能为空！');
            return false;
        }

        if (!this.ruleForm.startDate && !this.ruleForm.endDate) {
            this.yh_message_warn('"规则生效日期"不能为空！');
            return false;
        }

        if (!this.ruleForm.startTime && this.ruleForm.executionMethod == '0') {
            this.yh_message_warn('"发送时间点"不能为空！');
            return false;
        }

        console.log(this.ruleForm.limitTimes, 'this.ruleForm.limitTimes');

        let reg = /^[1-9]\d*$/g;
        if (!reg.test(this.ruleForm.limitTimes)) {
            // this.$message({ type: 'warning', message: '通知次数上限不能小于1！' });
            // return false; 为空默认为不设置上限
        }
        if (this.ruleForm.limitTimes < 1 && this.ruleForm.executionMethod == '0') {
            this.yh_message_warn('自动通知次数上限不能小于1！');
            return false;
        }
        if (!this.ruleForm.noticeUser.length && !this.ruleForm.notifier.length && this.ruleForm.noticeType != '15') {
            this.yh_message_warn('"接收角色"和"主送用户"不能同时为空！');
            return false;
        }
        return true;
    }

    getStyle(value: string): any {
        let color = '';
        color = value == '0' ? 'green' : value == '1' ? 'red' : '';
        return { color: color };
    }
}
</script>
<style lang="scss" scoped>
#notice-detail {
    .card-box {
        margin-bottom: 10px;
        .form-box {
            min-height: 270px;
            height: calc(100vh - 133px);
            // .left-label {
            //     /deep/ .el-form-item__label {
            //         width: 80px !important;
            //     }
            //     /deep/ .el-form-item__content {
            //         margin-left: 80px !important;
            //     }
            // }
            /deep/ .el-form-item__label {
                color: black;
            }
            /deep/ .el-date-editor .el-range-separator {
                padding: 0 15px;
            }
        }

        .btns {
            display: inline;
            float: right;
            padding-bottom: 20px;
        }
    }
}

/deep/ .el-select__tags-text {
    display: inline-block;
    max-width: 70px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
/deep/ .el-tag__close.el-icon-close {
    top: -5px;
}

.red-color {
    /deep/.el-input__inner,
    /deep/.el-input-group__append {
        color: red !important;
    }
}

.green-color {
    /deep/.el-input__inner,
    /deep/.el-input-group__append {
        color: #1c8d1c !important;
    }
}
</style>
